import { Button, Card, Form, Input, Select, Space, Table } from 'antd'
import {SearchOutlined} from '@ant-design/icons';
import React, {useEffect, useState} from 'react'
import { ColumnsType } from 'antd/lib/table';
import { CityOrDistrictResponse, HosTypesResponse, HospitalListItem, ProvinceResponse } from '@/api/hospital/model/hospitalListTypes';
import { reqGetAllProvinces, reqGetCityOrDistrict, reqGetHosTypes, reqGetHospitalList, reqUpdateHospitalStatus } from '@/api/hospital/hospitalList';
import { Link } from 'react-router-dom';

const { Option } = Select;

export default function HospitalList() {
  //声明表格的结构
  let columns: ColumnsType<HospitalListItem> = [
    {
      title: '序号',
      render: (_, record, index) => {
        return index + 1
      }
    },
    {
      title: '医院 logo',
      dataIndex: 'logoData',
      render: (v) => {
        return <img width={60} src={'data:image/png;base64,' + v} alt="" />
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname'
    },
    {
      title: '医院等级',
      // dataIndex: 'hostype'
      render: (_, record) => {
        return record.param.hostypeString;
      }
    },
    {
      title: '详细地址',
      // dataIndex: 'address'
      render: (_, record) => {
        return record.param.fullAddress;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (v) => {
        return v===1 ? '已上线' : '未上线';
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      render: (_, record) => {
        return <Space>
          <Link to={`/syt/hospital/hospitalList/${record.id}`}><Button type="primary">查看</Button></Link>
          <Link to={'/syt/hospital/schedule'} state={{hoscode: record.hoscode}}><Button type="primary">排班</Button></Link>
          
          <Button type="primary" onClick={async () => {
            await reqUpdateHospitalStatus(record.id, record.status ? 0 : 1);
            setFresh(fresh => !fresh);
          }}>{record.status ? '下线' : '上线'}</Button>
          
        </Space>
      }
    }
  ];

  //创建 form 对象
  let [form] = Form.useForm();

  //声明省份的状态
  let [provinces, setProvinces] = useState<ProvinceResponse>([]);
  //声明城市的状态
  let [cities, setCities] = useState<CityOrDistrictResponse>([]);
  //声明区县的状态
  let [districts, setDistricts] = useState<CityOrDistrictResponse>([]);
  //声明医院类型的状态
  let [hostypes, setHostypes] = useState<HosTypesResponse>([]);
  //声明状态表示表格中呈现的医院数据
  let [hospitals, setHospitals] = useState<HospitalListItem[]>([]);
  //声明与分页相关的状态
  let [current,setCurrent] = useState<number>(1);
  let [pageSize, setPageSize] = useState<number>(5);
  let [total, setTotal] = useState<number>(0);
  //加载loading状态
  let [loading, setLoading] = useState<boolean>(false);
  //定义 fresh
  let [fresh, setFresh] = useState<boolean>(false);

  //useEffect 发送初始化请求
  useEffect(() => {
    let getProvince = async () => {
      //发送请求获取所有的省份
      let provinces = await reqGetAllProvinces();
      //更新状态
      setProvinces(provinces);
    }
    getProvince();
  }, []);

  useEffect(() => {
    let getHostypes = async () => {
      //发送请求获取所有的省份
      let hostypes = await reqGetHosTypes();
      //更新状态
      setHostypes(hostypes);
    }
    getHostypes();
  }, []);

  //获取城市的事件回调
  let getCity = async (provinceID: React.Key) => {
    //重置 city 城市的值
    form.setFieldsValue({cityCode: undefined, districtCode: undefined});
    //清空城市列表
    setCities([]);
    //清空区县列表
    setDistricts([]);
    //获取省份的 id
    let cities = await reqGetCityOrDistrict(provinceID as number);
    //渲染
    setCities(cities);
  }

  //获取区县的事件回调
  let getDistrict = async (cityID: React.Key) => {
    //清空城市的数据
    form.setFieldsValue({districtCode: undefined});
    //清空区县的列表
    setDistricts([]);
    //获取城市对应的区县
    let districts = await reqGetCityOrDistrict(cityID as number);
    //输出
    // console.log(districts);
    //更新状态
    setDistricts(districts);
  }

  //组件挂载完毕, 获取医院列表数据
  useEffect(() => {
    let getHospital = async () => {
      //获取表单元素中的值
      let fields = form.getFieldsValue();
      console.log(fields);
      
      setLoading(true);
      //发送请求获取医院数据
      let result = await reqGetHospitalList({page: current, limit: pageSize, ...fields});
      //更新医院列表的状态
      setHospitals(result.content);    
      //更新医院列表的总数
      setTotal(result.totalElements);
      setLoading(false);
    }
    getHospital();
  }, [current, pageSize, fresh]);

  //声明 finish 函数 表单提交的事件回调
  let finish = async () => {
    setFresh(fresh => !fresh);
    setCurrent(1);
  };
  //声明 reset 函数
  let reset = () => {
    //手动清空表单元素的值
    // form.setFieldsValue({
    //   cityCode: undefined,
    //   districtCode: undefined,
    //   hoscode: undefined,
    //   hosname: undefined,
    //   hostype: undefined,
    //   provinceCode: undefined,
    //   status: undefined,
    // });
    //调用方法 清空表单元素的值 (简便操作)
    form.resetFields();
    //更新状态 重新加载组件
    setFresh(fresh => !fresh);
    //重置页码数为 1
    setCurrent(1);
  }

  return (
    <Card>
      {/* 表单部分 */}
      <Form
        form={form}
        layout={'inline'}
        onFinish={finish}
      >
        <Form.Item name="provinceCode" style={{width: 200, marginBottom: 20}}>
          <Select
            placeholder="请选择省"
            onChange={getCity}
          >
            {
              provinces.map(item => {
                return <Option key={item.id} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item name="cityCode" style={{width: 200}}>
          <Select
            placeholder="请选择市"
            onChange={getDistrict}
          >
            {
              cities.map(item => {
                return <Option key={item.id} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item name="districtCode" style={{width: 200}}>
          <Select
            placeholder="请选择区"
          >
            {
              districts.map(item => {
                return <Option key={item.id} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item name={'hosname'}>
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name={'hoscode'}>
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype" style={{width: 200}}>
          <Select
            placeholder="选择医院类型"
          >
            {
              hostypes.map(item => {
                return <Option key={item.id} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item name="status" style={{width: 200}}>
          <Select
            placeholder="医院状态"
          >
            <Option value="0">未上线</Option>
            <Option value="1">已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item >
          <Button type="primary" htmlType='submit' icon={<SearchOutlined />}>查询</Button>
        </Form.Item>
        <Form.Item>
          <Button htmlType='reset' onClick={reset}>清空</Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table 
        rowKey={'id'} 
        bordered 
        columns={columns} 
        dataSource={hospitals}
        loading={loading}
        pagination={{
          current,
          pageSize,
          total,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          onChange: (page, pageSize) => {
            //更新状态
            setCurrent(page);
            setPageSize(pageSize);
          }
        }}
        />
    </Card>
  )
}
